#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#define BUFFERSIZE 1024
using namespace std;

void headler(int signno)
{
    cout<<"get a signal"<<endl;
}

//测试代码：测试当匿名管道读端关闭，写端正常的退出是不是异常退出，有没有收到信号
// 进程异常退出必定包含信号
int main()
{
    signal(13,headler);
    int pipefd[2];
    pipe(pipefd);
    pid_t id = fork();
    if(id == 0)
    {
        close(pipefd[1]);
        int i = 1;
        char buffer[BUFFERSIZE];
        while(i)
        {
            if(i == 5)
            {
                break;
            }
            int n = read(pipefd[0],buffer,sizeof(buffer));
            cout<<buffer<<endl;
            i++;
        }
        close(pipefd[0]);
        exit(0);
    }
    //father
    
    close(pipefd[0]);
    string str("hello linux");
    while(true)
    {
        write(pipefd[1],str.c_str(),str.size());
        sleep(1);
    }

    waitpid(id,nullptr,0);
    return 0;
}